package logic

import (
	"context"
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/goccy/go-json"
	"github.com/zeromicro/go-zero/core/logx"
	"io"
	"net/http"
	"net/url"
	"strings"
	"user_srv/internal/svc"
	"user_srv/user"
)

type GetLogisticsTraceLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetLogisticsTraceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetLogisticsTraceLogic {
	return &GetLogisticsTraceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetLogisticsTraceLogic) GetLogisticsTrace(in *user.GetLogisticsTraceRequest) (*user.GetLogisticsTraceResponse, error) {
	// todo: add your logic here and delete this line

	// 快递100配置（换成你自己的）
	customer := "D941506934BB01526D7280AC39409CDB"
	key := "YayMZOQY8293"

	param := fmt.Sprintf(`{"com":"%s","num":"%s"}`, in.CompanyCode, in.TrackingNumber)
	sign := md5sum(param + key + customer)

	values := url.Values{}
	values.Set("param", param)
	values.Set("customer", customer)
	values.Set("sign", sign)
	reqURL := "https://poll.kuaidi100.com/poll/query.do?" + values.Encode()

	resp, err := http.Get(reqURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var result struct {
		Message string `json:"message"`
		State   string `json:"state"`
		Data    []struct {
			Time     string `json:"time"`
			Context  string `json:"context"`
			Location string `json:"location"`
		} `json:"data"`
	}

	if err := json.Unmarshal(body, &result); err != nil {
		return nil, err
	}

	var traces []*user.TraceItem
	for _, d := range result.Data {
		traces = append(traces, &user.TraceItem{
			Time:        d.Time,
			Description: d.Context,
			Location:    d.Location,
		})
	}

	return &user.GetLogisticsTraceResponse{
		Traces: traces,
		Status: result.State,
	}, nil
}

func md5sum(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	return strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
}
